﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PluoloadDemo.Controllers
{
    public class FileController : Controller
    {
        /// <summary>
        ///  封装的图片上传控件
        ///  custom-plupload
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult Plupload()
        {
            return View();
        }

        public ActionResult PluploadQueue()
        {
            return View();
        }

        /// <summary>
        ///  不使用拆分的上传文件
        ///  ASP 的限制下不能传太大的文件
        ///  chunk = null
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploaderWIthNoChunk(int? chunk, string name, string controllerName)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Upload\");
            var files = Request.Files[0];

            chunk = chunk ?? 0;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var fs = new FileStream(Path.Combine(path, name), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                var buffer = new byte[files.InputStream.Length];
                files.InputStream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
            }

            return Json(new { text = "上传成功", path = @"\Upload\" + name });
        }

        /// <summary>
        ///  上传文件
        /// </summary>
        /// <param name="chunk"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Uploader(int? chunk, string name, string controllerName)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Upload\");
            var files = Request.Files[0];

            chunk = chunk ?? 0;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var fs = new FileStream(Path.Combine(path, name), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                var buffer = new byte[files.InputStream.Length];
                files.InputStream.Read(buffer, 0, buffer.Length);
                fs.Write(buffer, 0, buffer.Length);
            }

            return Json(new { text = "上传成功", path = @"\Upload\" + name });
        }
    }
}